package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@Component
public class RedisIdWorker {
    private StringRedisTemplate stringRedisTemplate;
    private static final Long BEGIN_TIMESTAMP = 1735689600L;
    private static final int COUNT_BITS = 32;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefix) {
        //生时间戳
        LocalDateTime now = LocalDateTime.now();
        //把当前时间转换成秒
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        //当前时间-开始时间
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        //生成序列号
        //获取当天日期
        String data = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //redis自增长
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + data);
        //拼接返回id
        return timestamp << COUNT_BITS | count;
    }


}
